<template>
	<el-radio-group v-model="value" v-bind="$attrs">
		<component :is="componentName" v-for="item in options_" :key="item[valueName]" :label="item[valueName]">{{
			item[labelName]
		}}</component>
	</el-radio-group>
</template>

<script setup lang="ts" name="DictRadio">
import { ref, computed, watchEffect } from 'vue'
import dict from '@/utils/dict/index'

type Optioin = { [key: string]: any }

// 默认值
let props = withDefaults(
	defineProps<{
		options?: Optioin[] // 字典列表
		dict?: string // 字典类型 code
		modelValue?: string | number // 值
		labelName?: string // label 字段名
		valueName?: string // value 字段名
		isButton?: boolean // 是否是按钮样式
	}>(),
	{
		labelName: 'label',
		valueName: 'value',
		isButton: false
	}
)
// vmodel
const emits = defineEmits(['update:modelValue'])
const value = computed({
	get() {
		return props.modelValue
	},
	set(newVal) {
		emits('update:modelValue', newVal)
	}
})

let componentName = computed(() => {
	return props.isButton ? 'el-radio-button' : 'el-radio'
})

let options_ = ref<Optioin[]>([])
watchEffect(() => {
	if (props.dict) {
		dict.$cache.getDict(props.dict).then((result: Optioin[]) => {
			options_.value = result
		})
	} else if (props.options) {
		options_.value = props.options
	}
})
</script>
<style scoped lang="scss"></style>
